package com.fare.taluo.core.domain.thread;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.util.PDFTextStripper;

import com.fare.taluo.conf.PropertyUtils;
import com.fare.taluo.core.domain.config.city.PortEntity;
import com.fare.taluo.core.domain.config.line.FlightInfoEntity;
import com.fare.taluo.core.domain.crawl.CrawlPropertiesLoader;
import com.fare.taluo.core.domain.crawl.adapter.sub.HNAirLinePdfAdaptor;
import com.fare.taluo.util.DateUtils;

public class HNLinePdfParseThread extends Thread {
	
	@Override
	public void run() {
		PortEntity entity =  new PortEntity();
		InputStream input = null;
		HNAirLinePdfAdaptor adap = new HNAirLinePdfAdaptor(null);
		String url = "http://www.hnair.com/lxxx/hbskb/201005/P020130603327385934157.pdf";
		File pdfFile = null;
		int fetchCount = PropertyUtils.getIntProperty("crawl.line.fail.repeat.times", CrawlPropertiesLoader.CONFIG_FILE);
		try{
			while(fetchCount > 0){
				try {
					System.out.println("parsing is running...");
					pdfFile = (File) adap.fetch(url); 
				} catch (Exception e) {
					 fetchCount--;
					continue ;
					
				}
				System.out.println("the length of file is "+pdfFile.length());
				 if(pdfFile.length()>40000){
					 break;
				 }
		      fetchCount--;
				
		    }
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		PDDocument document = null;
		Map<String,PortEntity> allPorts = null;
		try {
			allPorts = entity.findPortEntityToMapByName();
			input = new FileInputStream(pdfFile);

			// 加载 pdf 文档

			document = PDDocument.load(input);

			/** 文档属性信息 **/

			PDDocumentInformation info = document.getDocumentInformation();

			// 获取内容信息
            String companyCode = "HU";
            String regex = "截止日期";
			PDFTextStripper pts = new PDFTextStripper();
			String content = pts.getText(document);
			List<List> listlist = new ArrayList<List>();
			
			String[] gridContent = content.split(regex);//将表头和表内容分开
			String[] records = gridContent[1].split("\r\n");
			for (int i = 1; i < records.length; i++) {
				String newString = records[i];
				String[] arrayString = newString.split(" ");
				//只保留信息齐全的航线
				if(arrayString.length == 8){
					
					List<String> list = new ArrayList<String>();
					list.add(arrayString[0]);//出发地 0
			        list.add(arrayString[1].substring(0, 2)+":"+arrayString[1].substring(2));//出发时间 1
			        list.add(arrayString[2].substring(0, 2)+":"+arrayString[2].substring(2));//到达时间 2
			        list.add(arrayString[3]);//目的地 4
			        list.add(companyCode+arrayString[4]);//航班号
			        list.add(arrayString[5]);//班次
			        String startDate = arrayString[6].replaceAll("[年月日]", "-");
			        list.add(startDate.substring(0, startDate.length()-1));//开始日期\
			        String endDate = arrayString[7].replaceAll("[年月日]", "-");
			        list.add(endDate.substring(0, endDate.length()-1));//截止日期
			        listlist.add(list);
				}
			}
			for (Iterator iterator = listlist.iterator(); iterator.hasNext();) {
				List<String> list = (List) iterator.next();
				FlightInfoEntity flightEntity = new FlightInfoEntity();
				PortEntity fromCity = allPorts.get(list.get(0));
				PortEntity toCity =  allPorts.get(list.get(3));
				if(fromCity != null && toCity != null){
					flightEntity.setFlightNo(list.get(4)); 
					flightEntity.setFrequence(list.get(5));
					
					if(list.get(0).equals("北京")){
						flightEntity.setFromCityName(list.get(0)+"(PEK)");	
					}else{
						flightEntity.setFromCityName(list.get(0));	
					}
					flightEntity.setFlightStartTime(list.get(1));
					flightEntity.setFlightEndTime(list.get(2));
					if(list.get(3).equals("北京")){
						flightEntity.setToCityName(list.get(3)+"(PEK)");	
					}else{
						flightEntity.setToCityName(list.get(3));	
					}
					
					if(fromCity.getCode().equals("NAY")){
						flightEntity.setFromCity("PEK");
					}else{
						flightEntity.setFromCity(fromCity.getCode());
					}
					
					if(toCity.getCode().equals("NAY")){
						flightEntity.setToCity("PEK");
					}else{
						flightEntity.setToCity(toCity.getCode());
					}
					
					flightEntity.setCompanyCode("HU");
					flightEntity.setCompanyName("海南航空");
					flightEntity.setEntryTime(new Date());
					flightEntity.setFlightDate(DateUtils.dateToStr(new Date(), "MM-dd"));
					flightEntity.setEffectStartTime(list.get(6));
					flightEntity.setEffectEndTime(list.get(7));
					 try {
						 flightEntity.tranSave(flightEntity);
						 System.out.println("it is saving...");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}			
			}
			System.out.println("---------finished---------");
			ThreadFlag.setIsFinish(true);
		} catch (Exception e){

			e.printStackTrace();
		} finally {

			if (null != input)
				try {
					input.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			if (null != document)
				try {
					document.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

		}	
	}
}
